from urlparse import urlparse, parse_qs

from django.db import models
from djangotoolbox.fields import ListField

from .fields import StringListField
from .globals import CONNECTION_RELATIONSHIP_TYPES, MONTH_CHOICES, PILLAR_STATES

class CategoryField(ListField):
    def formfield(self, **kwargs):
        return models.Field.formfield(self, StringListField, **kwargs)


class PosBase(models.Model):
    ### Base model for the app
    ###
    
    class Meta:
        abstract = True
        get_latest_by = "created"
    
    created = models.DateTimeField(auto_now_add=True, editable=False)
    modified = models.DateTimeField(auto_now=True, editable=False)


class DeathCount(PosBase):
    death_count = models.PositiveIntegerField()


class Pillar(PosBase):
    
    fb_id = models.CharField(max_length=50, verbose_name="Freebase ID", help_text="e.g. william_shakespeare", blank=True, null=True)
    name = models.CharField(max_length=50, help_text="e.g. William Shakepeare")
    importance = models.PositiveIntegerField(help_text="Integer, relative to other pillars", blank=True, null=True)

    categories = CategoryField(help_text="Comma separated (e.g. 'Family, General')")

    short_description = models.CharField(max_length=100, blank=True, null=True, help_text="Pref. around 10 words or less")
    long_description = models.TextField(blank=True, null=True)

    context_url = models.URLField(verbose_name="Context URL", blank=True, null=True)
    defection_url = models.URLField(verbose_name="Defection URL", blank=True, null=True)

    image_blobkey = models.CharField(max_length=255, editable=False, null=True)
    image_url = models.URLField(verify_exists=False, editable=False, null=True)

    state = models.CharField(max_length=50, choices=PILLAR_STATES)
    defection_date = models.DateField(blank=True, null=True, help_text="Format: yyyy-mm-dd")

    def context_youtube_id(self):
        url = None
        youtube_id = None
        if self.defection_url:
            url = urlparse(self.defection_url)
        if url and url.netloc == "www.youtube.com":
            url_querystring = parse_qs(url.query)
            youtube_id = url_querystring.get("v",None)
        if youtube_id:
            return youtube_id[0]
        if self.context_url:
            url = urlparse(self.context_url)
        if url and url.netloc == "www.youtube.com":
            url_querystring = parse_qs(url.query)
            youtube_id = url_querystring.get("v",None)
        if youtube_id:
            return youtube_id[0]
        else:
            return False

    def image(self, size):
        if self.image_url:
            return "%s=s%s" % (self.image_url, size)
        else:
            return None

    def image_thumbnail(self):
        return self.image(200)

    def image_tiny(self):
        return self.image(75)

    def __unicode__(self):
        return self.name
